package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.VIP_ZX_HorizontalListViewAdapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.bean.User_Wallet;
import com.jaya.budan.bean.VIP_JiLu;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.pay.zfb.PayResult;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.HorizontalListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class VIP_ZX_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener{

    private RelativeLayout back, rl_vip_zx_permission;
    private TextView gr_tv_nicename, gr_tv_id, gr_tv_money, tv_vip_zx_recharge;
    private ImageView iv_xyf_jilu, iv_vip_zx_logo, gr_iv_head;
    private String access_token;
    private HorizontalListView main_hlv, main_hlv_vip;
    private List<String> list_name;
    private List<Integer> list_icon;
    private int screenWidth, vip_id, mtype, position_1;
    private User_Limit user_limit;
    private ArrayList<VIP_JiLu> mlist = new ArrayList<>();
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToolUtils.showToast(VIP_ZX_Activity.this, "支付成功");
                        finish();
                    } else if (TextUtils.equals(resultStatus, "8000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToolUtils.showToast(VIP_ZX_Activity.this, "支付失败");
                    } else{
                        ToolUtils.showToast(VIP_ZX_Activity.this, "支付取消");
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_zx);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        user_limit = (User_Limit) intent.getSerializableExtra("user_limit");
        back = findViewById(R.id.back);
        rl_vip_zx_permission = findViewById(R.id.rl_vip_zx_permission);
        iv_xyf_jilu = findViewById(R.id.iv_xyf_jilu);
        gr_iv_head = findViewById(R.id.gr_iv_head);
        iv_vip_zx_logo = findViewById(R.id.iv_vip_zx_logo);
        gr_tv_nicename = findViewById(R.id.gr_tv_nicename);
        gr_tv_id = findViewById(R.id.gr_tv_id);
        gr_tv_money = findViewById(R.id.gr_tv_money);
        tv_vip_zx_recharge = findViewById(R.id.tv_vip_zx_recharge);
        main_hlv = findViewById(R.id.main_hlv);
        main_hlv_vip = findViewById(R.id.main_hlv_vip);
        back.setOnClickListener(this);
        rl_vip_zx_permission.setOnClickListener(this);
        iv_xyf_jilu.setOnClickListener(this);
        tv_vip_zx_recharge.setOnClickListener(this);
        gr_tv_nicename.setText("" + user_limit.getNicename());
        gr_tv_id.setText("ID：" + user_limit.getUid());
        if (user_limit.getIs_vip() == 1){
            iv_vip_zx_logo.setVisibility(View.VISIBLE);
            gr_tv_money.setVisibility(View.VISIBLE);
            gr_tv_money.setText("" + user_limit.getVip_time() + "到期");
        } else {
            iv_vip_zx_logo.setVisibility(View.GONE);
            gr_tv_money.setVisibility(View.GONE);
        }
        Glide.with(VIP_ZX_Activity.this).load(user_limit.getHead()).apply(new RequestOptions()
                .placeholder(R.mipmap.iv_main_item).error(R.mipmap.iv_main_item)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
        ).into(gr_iv_head);
        list_name = new ArrayList<>();
        list_icon = new ArrayList<>();
        list_name.add("隐身");
        list_name.add("无痕访问");
        list_name.add("悄悄查看消息");
        list_name.add("隐藏在线时间");
        list_name.add("隐藏距离");
        list_icon.add(R.mipmap.iv_vip_zx_1);
        list_icon.add(R.mipmap.iv_vip_zx_2);
        list_icon.add(R.mipmap.iv_vip_zx_3);
        list_icon.add(R.mipmap.iv_vip_zx_4);
        list_icon.add(R.mipmap.iv_vip_zx_5);
        // 获取屏幕宽高
        screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
        main_hlv.setAdapter(new VIP_ZX_HorizontalListViewAdapter(this, screenWidth, list_name, list_icon, 1, null, null));
        postData();
        main_hlv_vip.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LinearLayout ll_vip_zx_1 = view.findViewById(R.id.ll_vip_zx_1);
                ll_vip_zx_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        vip_id = mlist.get(position).getId();
                        position_1 = position;
                        CommonPopWindow.newBuilder()
                                .setView(R.layout.pop_vip_zx_pay)
                                .setAnimationStyle(R.style.AnimUp)
                                .setBackgroundDrawable(new BitmapDrawable())
                                .setSize(0, 1200)
                                .setViewOnClickListener(VIP_ZX_Activity.this)
                                .setBackgroundDarkEnable(true)
                                .setBackgroundAlpha(0.7f)
                                .build(VIP_ZX_Activity.this)
                                .showAsCenter(v);
                    }
                });
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_xyf_jilu:
                Intent intent = new Intent(this, VIP_ZX_JiLu_Activity.class);
                intent.putExtra("access_token", access_token);
                startActivity(intent);
                break;
            case R.id.rl_vip_zx_permission:
                Intent intent1 = new Intent(this, VIP_ZX_Permission_Activity.class);
                intent1.putExtra("access_token", access_token);
                startActivity(intent1);
                break;
            case R.id.tv_vip_zx_recharge:
                //立即续费
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    @SuppressLint({"SetTextI18n", "NonConstantResourceId"})
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_vip_zx_pay:
                TextView tv_vip_zx_title = view.findViewById(R.id.tv_vip_zx_title);
                TextView tv_vip_zx_price = view.findViewById(R.id.tv_vip_zx_price);
                CheckBox cb_register = view.findViewById(R.id.cb_register);
                CheckBox cb_register2 = view.findViewById(R.id.cb_register2);
                LinearLayout ll_wx = view.findViewById(R.id.ll_wx);
                LinearLayout ll_zfb = view.findViewById(R.id.ll_zfb);
                Button btn_login = view.findViewById(R.id.btn_login);
                tv_vip_zx_title.setText("不单会员×" + mlist.get(position_1).getTime() + "个月");
                tv_vip_zx_price.setText("¥" + mlist.get(position_1).getMoney());
                ll_wx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mtype = 2;
                        cb_register.setEnabled(true);
                        cb_register2.setEnabled(false);
                        cb_register.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                        cb_register2.setBackgroundResource(R.mipmap.iv_duihao_no);
                    }
                });
                ll_zfb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mtype = 3;
                        cb_register.setEnabled(false);
                        cb_register2.setEnabled(true);
                        cb_register.setBackgroundResource(R.mipmap.iv_duihao_no);
                        cb_register2.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                    }
                });
                btn_login.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        JSONObject object = new JSONObject();
                        try {
                            object.put("v_id", vip_id);
                            object.put("pay_type", mtype);//支付方式 1 默认支付 2微信 3支付宝
                            object.put("client_id", "1");//客户端 1 android 2 iOS
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        postVIPData(object);
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_vip_Url + access_token, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        mlist = gson.fromJson(info.toString(), new TypeToken<ArrayList<VIP_JiLu>>(){}.getType());
                        main_hlv_vip.setAdapter(new VIP_ZX_HorizontalListViewAdapter(VIP_ZX_Activity.this, screenWidth, list_name, list_icon, 2, mlist, null));
                    } else {
                        ToolUtils.showToast(VIP_ZX_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(VIP_ZX_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postVIPData(JSONObject object) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.gr_vip_CZ_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        if (mtype == 2){
                            ToolUtils.showToast(VIP_ZX_Activity.this, "微信支付");
                        } else if (mtype == 3){
                            String orderInfo = jsonObject.getString("info");
                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(VIP_ZX_Activity.this);
                                    Map<String, String> result = alipay.payV2(orderInfo, true);
                                    Log.i("msp", result.toString());
                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        }
                    } else {
                        ToolUtils.showToast(VIP_ZX_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(VIP_ZX_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }
}
